package com.school.fuyuan.business.service;

import com.school.fuyuan.business.constants.InfoConstants;
import com.school.fuyuan.business.mapper.PrivilegeMapper;
import com.school.fuyuan.business.mapper.RoleMapper;
import com.school.fuyuan.business.mapper.UserMapper;
import com.school.fuyuan.business.model.po.Privilege;
import com.school.fuyuan.business.model.po.User;
import com.school.fuyuan.business.model.vo.AddUserVo;
import com.school.fuyuan.business.model.vo.FollowUserOutVo;
import com.school.fuyuan.common.exception.CommonRuntimeException;
import com.school.fuyuan.common.message.RequestMsg;
import com.school.fuyuan.common.message.ResponseMsg;
import com.school.fuyuan.common.util.JsonUtils;
import com.school.fuyuan.common.util.ParameterUtils;
import com.school.fuyuan.common.util.TransformUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/5 22:40
 * @description
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrivilegeMapper privilegeMapper;
    @Autowired
    private RoleMapper roleMapper;


    public void updatePassword(@Valid RequestMsg<Map<String, String>> requestMsg, ResponseMsg responseMsg) {
        String userId = requestMsg.getHead().getUserId();
        String oldPassword = requestMsg.getData().get("oldPassword");
        String newPassword = requestMsg.getData().get("newPassword");
        User user = userMapper.getUser(userId);
        if (!user.getPassword().equals(oldPassword)) {
            throw new CommonRuntimeException("800", "用户密码错误，请确认后重新输入");
        }
        int result = userMapper.updatePassword(userId, newPassword);
        if (result == 0) {
            throw new CommonRuntimeException("-801", "修改失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addUser(AddUserVo addUserVo) {
        User user = TransformUtils.transform(addUserVo, User.class);
        int result;
        try {
            result = userMapper.register(user);
        } catch (DuplicateKeyException e) {
            throw new CommonRuntimeException("802", "用户已存在");
        }
        if (result == 0) {
            throw new CommonRuntimeException("-801", "修改失败");
        }
        String userId  = user.getUserId();
        String roleId = addUserVo.getRoleId();
        userMapper.addUserRole(userId, roleId);
    }

    public Map<String,Object> getFollowUsers(@Valid RequestMsg requestMsg) {
        List<User> users = userMapper.getUsers(0,0);
        List<FollowUserOutVo> userOutVos = TransformUtils.transformList(users, FollowUserOutVo.class);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", userOutVos);
        return resultMap;
    }

    public void updateUserRole(String userId, String roleId) {
        userMapper.updateRole(userId, roleId);
    }

    public Map<String, Object> login(String mobile, String password) {
        User user = userMapper.getUserByMobile(mobile);
        if (ParameterUtils.isEmpty(user)) {
            throw new CommonRuntimeException("803", "用户不存在");
        }
        if (!password.equals(user.getPassword())) {
            throw new CommonRuntimeException("803", "密码错误");
        }
        String userId = user.getUserId();
        List<Integer> privilegeIds = null;
        List<Integer> roleIds = roleMapper.getUserRole(userId);
        if (!ParameterUtils.isEmpty(roleIds)) {
            privilegeIds = roleMapper.getPrivileges(roleIds);
        }
        List<Privilege> privileges = null;
        if (!ParameterUtils.isEmpty(privilegeIds)) {
            privileges = privilegeMapper.getPrivileges(privilegeIds);
        }
        List<String> ids = userMapper.getApptIds(userId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("userId", userId);
        resultMap.put("privileges", privileges);
        resultMap.put("ids", ids);
        return resultMap;
    }

    public Map<String,Object> getUsers(RequestMsg requestMsg) {
        int pageNum = requestMsg.getHead().getPageNum();
        if (pageNum < 1) {
            pageNum = 1;
        }
        int pageSize = requestMsg.getHead().getPageSize();
        if (pageSize < 0) {
            pageSize = InfoConstants.DEFAULT_PAGE_SIZE;
        }
        int pageMin = (pageNum - 1) * pageSize;
        requestMsg.getHead().getPageNum();
        List<User> users = userMapper.getUsers(pageMin,pageSize);
        int counts = userMapper.getUsersCount();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", users);
        resultMap.put("counts", counts);
        return resultMap;
    }

    public void deleteUser(Integer userId) {
        userMapper.deleteUser(userId);
        userMapper.deleteUserRole(userId);
    }
}
